package com.ruoyi.mq.kafka.producer;

import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.crypto.symmetric.AES;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.mq.kafka.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;

import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.util.Random;

@Component
@Slf4j
public class O1TemperatureProducer {

    @Value("${kafka.topic.temperature}")
    private String topic;

    @Value("${rsa.publicKey}")
    private String publicKeyStr;

    @Value("${aes.key}")
    private String aesKey;

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    private Random random = new Random();
    private DecimalFormat df = new DecimalFormat("#.##");


    // 每5秒发送一次温度数据
    public void sendTemperatureData() {
        // 模拟温度数据 (15.0 - 35.0之间)
        double temperature = 15 + (35 - 15) * random.nextDouble();
        String message = "时间: " + LocalDateTime.now() + ", 温度: " + df.format(temperature) + "°C";

        ListenableFuture<SendResult<String, String>> send = kafkaTemplate.send(topic, message);
        send.addCallback(new ListenableFutureCallback<SendResult<String, String>>() {
            @Override
            public void onFailure(Throwable ex) {
                log.error("消息发送失败: message={}, error={}", message, ex.getMessage());
            }

            @Override
            public void onSuccess(SendResult<String, String> result) {
                log.info("消息发送成功: topic={}, offset={}", topic, result.getRecordMetadata().offset());

            }
        });
        System.out.println("生产者发送消息: " + message);
    }


    public void sendTemperatureWithRsa() {
        try {
            // 1. 创建RSA实例，可以传入自己的公私钥，不传则自动生成
            RSA rsa = new RSA(null,publicKeyStr);
            AES aes = new AES(aesKey.getBytes());

            // 创建用户对象
            User user = new User();
            String idCard = "123456199001011234"; // 示例身份证号
            String encryptedIdCard = rsa.encryptBase64(idCard, KeyType.PublicKey);
            log.info("加密后的身份证是：{}",encryptedIdCard);
            user.setId(1L);
            user.setUserName("张三");
            user.setUserId("zhangsan");
            user.setIdCard(encryptedIdCard);

            // 将 User 对象转换为 JSON 字符串（需引入 Jackson 或 Gson）
            String userJson = new ObjectMapper().writeValueAsString(user);

            String encryptedUserJson =  aes.encryptBase64(userJson);
            // 发送加密后的用户信息
            kafkaTemplate.send(topic, "user", encryptedUserJson);

            System.out.println("发送加密用户信息: " + userJson);
        } catch (Exception e) {
            log.error("RSA 加密或消息发送失败: ", e);
        }

    }
}
